﻿using HCLSMod;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using ZLSerialPortBusLib.PLCManager;

namespace ZLSerialPortBusLib.LogView
{
    public partial class FLogView : Form
    {
        public static bool LogViewRunning = false;
        public static Form LogViewFrom { get; set; }

        const int WM_VSCROLL = 0x0115;
        const int SB_BOTTOM = 7;

        [DllImport("user32.dll", EntryPoint = "SendMessage")]
        public static extern int SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);

        private ZLPLCBusOnSerialPort fSerialPLC { get; set; }
        public FLogView(ZLPLCBusOnSerialPort fSerialPLCX)
        {
            InitializeComponent();
            fSerialPLC = fSerialPLCX;
            LogViewRunning = true;
            LogViewFrom = this;
        }

        private void fDeamon_Tick(object sender, EventArgs e)
        {
            if (fSerialPLC != null)
            {
                if (fSerialPLC.Active)
                {
                    if (fSerialPLC.SerialPortModbus != null)
                    {
                        if (fSerialPLC.SerialPortModbus.TxDataCount > 0)
                        {
                            ZLByteDataRecord fTxData = fSerialPLC.SerialPortModbus.LastTxData;
                            richTextBoxRunInfo.AppendText(fTxData.ToString("Tx") + "\r");
                        }
                        if (fSerialPLC.SerialPortModbus.RxDataCount > 0)
                        {
                            ZLByteDataRecord fRxData = fSerialPLC.SerialPortModbus.LastRxData;
                            richTextBoxRunInfo.AppendText(fRxData.ToString("Rx") + "\r");
                        }
                        if (checkBoxLogAuto.Checked)
                            SendMessage(richTextBoxRunInfo.Handle, WM_VSCROLL, SB_BOTTOM, 0);
                    }
                }
            }
        }

        public void SetParent(Control fParent)
        {
            this.FormBorderStyle = FormBorderStyle.None;
            this.Dock = DockStyle.Fill;
            this.TopLevel = false;
            this.Parent = fParent;
            this.Show();
        }

        public void CloseAll(bool fHasClose = false)
        {
            fSerialPLC = null;
            LogViewRunning = false;
            LogViewFrom = null;
            if (!fHasClose)
                Close();
        }

        public void ClearAll()
        {
            richTextBoxRunInfo.Clear();
        }

        private void buttonClearAll_Click(object sender, EventArgs e)
        {
            ClearAll();
        }

        private void FLogView_FormClosed(object sender, FormClosedEventArgs e)
        {
            CloseAll(true);
        }
    }
}
